<template>
	<view class="autograph">
		<canvas class="myCanvas" canvas-id="myCanvas" @touchstart="touchstart" @touchmove="touchmove"
			@touchend="touchend"></canvas>
		<view class="footer">
			<view class="right" @click="clear">清除</view>
      <view class="left" @click="finish">保存</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				ctx: '',
				//路径点集合
				points: [],
				//签名图片
				SignatureImg: ''
			}
		},
		created() {
			this.createCanvas()
		},
		methods: {
			createCanvas() {
				//创建绘图对象
				this.ctx = uni.createCanvasContext('myCanvas', this);
				//设置画笔样式
				this.ctx.lineWidth = 4;
				this.ctx.lineCap = 'round';
				this.ctx.lineJoin = 'round';
			},
			touchstart(e) {
				let startX = e.changedTouches[0].x;
				let startY = e.changedTouches[0].y;
				let startPoint = {
					X: startX,
					Y: startY
				};
				this.points.push(startPoint);
				//每次触摸开始，开启新的路径
				this.ctx.beginPath();
			},
			touchmove(e) {
				let moveX = e.changedTouches[0].x;
				let moveY = e.changedTouches[0].y;
				let movePoint = {
					X: moveX,
					Y: moveY
				};
				this.points.push(movePoint); //存点
				let len = this.points.length;
				if (len >= 2) {
					this.draw(); //绘制路径
				}
			},
			touchend() {
		 	this.points = [];
			},
			draw() {
				let point1 = this.points[0];
				let point2 = this.points[1];
				this.points.shift();
				this.ctx.moveTo(point1.X, point1.Y);
				this.ctx.lineTo(point2.X, point2.Y);
				this.ctx.stroke();
				this.ctx.draw(true);
			},
			clear() {
				let that = this;
				uni.getSystemInfo({
					success: function(res) {
						let canvasw = res.windowWidth;
						let canvash = res.windowHeight;
						that.ctx.clearRect(0, 0, canvasw, canvash);
						that.ctx.draw(true);
					}
				});
			},
			finish() {
				let that = this;
				uni.canvasToTempFilePath({
					canvasId: 'myCanvas',
					success: function(res) {
						//这里的res.tempFilePath就是生成的签字图片
						console.log(res.tempFilePath);
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	.autograph {
    display: flex;
    flex-direction: column;
		.myCanvas {
      width: 100vw;
			height: 85vh;
		}
    .footer{
      flex: 1;
      display: flex;
      justify-content: space-around;
      .left,.right{
        color: #FFF;
        height: 40px;
        line-height: 40px;
        text-align: center;
        border-radius: 10rpx;
        width: 40%;
        background: #3c9cff;
      }
      .right{
        background: #f9ae3d;
      }
    }
	}
</style>
